package leetcode.code1360;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	static int[] days1 = new int[] { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	static int[] days2 = new int[] { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	static int[] days1s;
	static int[] days2s;

	static {
		days1s = new int[13];// i月之前一共有多少天，平年
		days2s = new int[13];// i月之前一共有多少天，闰年
		for (int i = 1; i < 13; i++) {
			days1s[i] = days1s[i - 1] + days1[i - 1];
			days2s[i] = days2s[i - 1] + days2[i - 1];
		}
	}

	public boolean isLeapYear(int year) {
		return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
	}

	public int days1900(int lastYear) {
		int base = 1970;
		if (lastYear <= base) {
			return 0;
		}
		return (lastYear - base) * 365 + distance(lastYear, base, 4) - distance(lastYear, base, 100)
				+ distance(lastYear, base, 400);
	}

	public int distance(int num1, int num2, int by) {
		return num1 / by - num2 / by;
	}

	public int daysBetweenDates(String date1, String date2) {
		String[] d1 = date1.split("-");
		String[] d2 = date2.split("-");
		int day1 = day2(Integer.valueOf(d1[0]), Integer.valueOf(d1[1]), Integer.valueOf(d1[2]));
		int day2 = day2(Integer.valueOf(d2[0]), Integer.valueOf(d2[1]), Integer.valueOf(d2[2]));
		return Math.abs(day1 - day2);
	}

	private int day2(int year, int month, int day) {
		int ans = days1900(year - 1);
		boolean isLeapYear = isLeapYear(year);
		if (isLeapYear) {
			ans += days2s[month];
		} else {
			ans += days1s[month];
		}
		ans += day;
		return ans;
	}

	@Override
	public void debug4() {
		HelpDebug.compare(367, this.daysBetweenDates("1971-06-29", "1972-06-30"));
		HelpDebug.compare(15, this.daysBetweenDates("2020-01-15", "2019-12-31"));
		HelpDebug.compare(1, this.daysBetweenDates("2019-06-29", "2019-06-30"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
